package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author zhai
 * @date 2025-01-02
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    /**
     * 申请入住
     *
     * @param checkInApplyDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1.校验老人是否入住，如果入住直接结束
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        wrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
                        .in(Elder::getStatus,1,4);
        Elder elder = elderMapper.selectOne(wrapper);

        if (ObjectUtil.isNotEmpty(elder)){
            throw new BaseException("老人已经入住，不可以提交重复信息");
        }
        //2.如果老人未入住，更新床位状态为已入住
        Long bedId = checkInApplyDto.getCheckInConfigDto().getBedId();
        Bed bed = bedMapper.selectById(bedId); //根据床位id查看床位对象
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //3.新增或者更新老人基本信息
         elder = InsertAndUpdateElder(checkInElderDto, bed);
        //4.新增签约办理
        InsertContract(elder,checkInApplyDto.getCheckInContractDto(),checkInApplyDto.getCheckInConfigDto());
        //5.新增入住信息
        CheckIn checkIn = InsertCheckIn(elder, checkInApplyDto.getCheckInConfigDto(), bed, checkInApplyDto.getElderFamilyDtoList());
        //6.新增入住配置
        InsertCheckInConfig(checkIn,checkInApplyDto.getCheckInConfigDto());
    }

    /**
     * 新增入住配置信息
     * @param checkIn  入住信息
     * @param checkInConfigDto  入住配置信息
     */
    private void InsertCheckInConfig(CheckIn checkIn, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        checkInConfig.setCheckInId(checkIn.getId());
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     *
     * @param elder              老人信息
     * @param checkInConfigDto   入住配置
     * @param bed                床位信息
     * @param elderFamilyDtoList
     */
    private CheckIn InsertCheckIn(Elder elder, CheckInConfigDto checkInConfigDto,
                                  Bed bed, List<ElderFamilyDto> elderFamilyDtoList) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        BeanUtils.copyProperties(checkInConfigDto,checkIn);
        checkIn.setBedNumber(bed.getBedNumber());
        //家属信息
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增签约办理
     * @param elder 老人信息
     * @param checkInContractDto 合同信息
     * @param checkInConfigDto    入住配置信息
     */
    private void InsertContract(Elder elder, CheckInContractDto checkInContractDto, CheckInConfigDto checkInConfigDto) {
        Contract contract = new Contract();
        contract.setElderId(Integer.valueOf(String.valueOf(elder.getId()))); //获得老人的id
        contract.setElderName(elder.getName());  //获取老人姓名
        contract.setStartDate(checkInConfigDto.getStartDate());  //获得入住配置的开始时间
        contract.setEndDate(checkInConfigDto.getEndDate());   //获得入住配置的结束时间
        BeanUtils.copyProperties(checkInContractDto,contract); //拷贝合同的信息
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contractMapper.insert(contract);
    }

    /**
     * 新增或者更新老人基本信息
     * @param checkInElderDto 老人的基本信息
     * @param bed           床位的基本信息
     * @return              结果
     */

    private Elder InsertAndUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        //判断是新增还是修改
        String idCardNo = checkInElderDto.getIdCardNo();
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo,idCardNo);
        Elder elder = elderMapper.selectOne(wrapper);
        if(ObjectUtil.isNotEmpty(elder)){
            //修改老人的基本信息
            //更新床位状态为1
            elder.setStatus(1);
            //更新前传递过来的其他基本信息
            BeanUtils.copyProperties(checkInElderDto,elder);
            //更新后的床位id和床位编号
            elder.setBedId(bed.getId());
            elder.setBedNumber(bed.getBedNumber());
            elderMapper.updateById(elder);
        }else {
            //新增老人的基本信息
            //new一个老人的基本信息
            elder = new Elder();
            //设置老人的床位状态为1
            elder.setStatus(1);
            //拷贝传递过来的其他基本信息
            BeanUtils.copyProperties(checkInElderDto,elder);
            //给新老人设置床位id和床位编号
            elder.setBedId(bed.getId());
            elder.setBedNumber(bed.getBedNumber());
            elderMapper.insert(elder);
        }
        return elder;
    }

    /**
     * 查询入住信息
     *
     * @param id 根据id查询入住信息
     * @return 返回结果
     */
    @Override
    public CheckInDetailVo getCheckInDetail(Long id) {
        //通过CheckInDetailvO获取四个表单
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //根据入住id获取入住信息
        CheckIn checkIn = checkInMapper.selectById(id);
        //通过入住信息获取老人的id
        Long elderId = checkIn.getElderId();
        //根据老人id获取到老人的基本信息
        Elder elder = elderMapper.selectById(elderId);
        //将老人的信息拷贝到老人VO中
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);

        //根据身份证获取老人的年龄
/*        String idCardNo = elder.getIdCardNo();
        if (idCardNo != null && idCardNo.length() == 18) {
            String birthDateStr = idCardNo.substring(6, 14);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            LocalDate birthDate = LocalDate.parse(birthDateStr, formatter);
            LocalDate currentDate = LocalDate.now();
            int age = Period.between(birthDate, currentDate).getYears();
            checkInElderVo.setAge(age);
        }*/
        //根据身份证获取老人的年龄
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo);



        //将家属信息通过JOSN转换list传递给前端
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);

        //将入住配置信息和入住信息传递给前端
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>()
                .eq(CheckInConfig::getCheckInId, id));
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);

        //将合同信息传递前端
        Contract contract = new Contract();
        Contract contract1 = contractMapper.selectOne(new LambdaQueryWrapper<Contract>()
                .eq(Contract::getElderId, elderId));
        BeanUtils.copyProperties(contract1,contract);
        checkInDetailVo.setContract(contract);

        //返回整数结果
        return checkInDetailVo;

    }
}


